<?php
namespace app\kucun\controller;

use app\kucun\model\WxWorkUserModel;
use QiyeWork\QiyeWorkService;

/**
 * Class Index
 * @package app\index\controller
 */
class QiyeWork extends Base
{

    private $config = [
        'corpid' => 'ww4d5c7d4b4abd5ea0',
        
        'agentid' => 1000002, // 如果有 agend_id 则填写
        'secret'   => 'YsmNa9_l8-AkV86uAoqPJeDBmXyFG8xu-UHz34_NFUA',
    
        // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        'response_type' => 'array',
    ];


    public function __construct(\think\App $app)
    {
        parent::__construct($app);
    }


    public function getUser(){
        $this->checkUserLogin();
        return $this->returnSuccess($this->user);
    }



    public function getCorpJsConfig(){
        $qiyeWork = new QiyeWorkService($this->config);
        $url = input('url', '', 'string');
        $result = $qiyeWork->getJsapiSign($url, ['chooseImage','scanQRCode']);
        echo json_encode($result);
    }

    public function getAgentJsConfig(){
        $qiyeWork = new QiyeWorkService($this->config);
        $url = $_SERVER['HTTP_REFERER'];
        $url = input('url', '', 'string');
        $result = $qiyeWork->getAgentConfigSign($url, ['getCurExternalChat', 'sendChatMessage','scanQRCode']);
        echo json_encode($result);
    }




    // 企业微信web授权登录
    public function getLoginUrl(){
        $qiyeWork = new QiyeWorkService($this->config);
        $url = input('url', '', 'string');
        if(!$url) $url = $_SERVER['HTTP_REFERER'];
        $result = $qiyeWork->getLoginUrl($url);
        return $this->returnSuccess(['url' => $result]);
    }


    // 这里我计划加一个中转页面，记录来之前的页面地址。然后再跳转到企业微信登录页面，全部登录完成后，再跳转到之前的页面
    public function login(){
        $origin_url = $_SERVER['HTTP_REFERER'];
        session('origin_url', $origin_url);
        $qiyeWork = new QiyeWorkService($this->config);
        $tmp_wx_url = url('kucun/QiyeWork/getUserinfo', [], "", true);
        $url = $qiyeWork->getLoginUrl($tmp_wx_url);
        header('Location: ' . $url);

    }


    public function getUserInfo(){
        $code = input('code', '', 'string');
        $qiyeWork = new QiyeWorkService($this->config);
        $result = $qiyeWork->getUserInfo($code);
        // dump($result);
        $userinfo = $qiyeWork->getUser($result['UserId']);
        // dump($userinfo);
        $wxworkUser = WxWorkUserModel::where(['userId' => $userinfo['userid']])->find();

        if(!$wxworkUser){
            $wxworkUser = WxWorkUserModel::create([
                'userid' => $userinfo['userid'],
                'name' => $userinfo['name'],
            ]);
        }
        $origin_url = session('origin_url');
        $token = md5($result['UserId'] . time());
        cache($token, $wxworkUser, 3600 * 24 * 7);
        // 将登录信息写入cookie
        cookie("login_info", $wxworkUser);
        header('Location: ' . $origin_url . '?token=' . $token);
    }
    

}
